package com.hyt.it.ogt.kq.service.gov.service.obs;

import com.hyt.it.ogt.kq.common.config.exception.KqException;
import com.hyt.it.ogt.kq.common.gov.utils.HuaweiCloudObsUtil;
import com.obs.services.model.ObjectMetadata;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 刘恒活
 * @since 2021/8/31 17:12
 */
@Component
public class CloudObsService {

    /**
     * @param path 不能以“/”开头
     * @param file
     * @return 返回网络下载全路径
     */
    public String updateFile(String path, File file) throws IOException {
        return HuaweiCloudObsUtil.uploadFile(path, this.file2InputStream(file));
    }

    /**
     * 上传文件
     *
     * @param path        不能以“/”开头
     * @param inputStream
     * @return
     */
    public String updateFile(String path, InputStream inputStream) {
        return HuaweiCloudObsUtil.uploadFile(path, inputStream);
    }

    public void deleteFile(String path) throws KqException {
        HuaweiCloudObsUtil.deleteFile(path);
    }

    public InputStream downFile(String path) {
        return HuaweiCloudObsUtil.getInputStream(path);
    }

    public ObjectMetadata getFileMetaData(String path) {
        return HuaweiCloudObsUtil.getObjectMetadata(path);
    }

    private InputStream file2InputStream(File file) throws IOException {
        return this.bytes2InputStream(FileUtils.readFileToByteArray(file));
    }

    private InputStream bytes2InputStream(byte[] bytes) {
        return new ByteArrayInputStream(bytes);
    }
}
